package com.zmc.common.config;


import com.zmc.common.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @Author：zmc
 * @Date：2024/10/16 10:28
 * Feign异步调用丢失请求头问题：
 *      解决方案： 1、先获取： RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
 *               2、异步编排时，每一个线程都来共享之前的请求数据 即：
 *               CompletableFuture执行异步时，每次调用feign请求时，加入： RequestContextHolder.setRequestAttributes(requestAttributes);
 *               否则，请求头丢失，获取不到。
 */

@Configuration
public class FeignRequestConfiguration {

    @Bean
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
                ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    String token = request.getHeader(AuthConstants.JWT_HEADER);
                    if (token != null) {
                        template.header(AuthConstants.JWT_HEADER, token);
                    }
                }
            }
        };
    }
}
